package cn.roadtrip.utilupload.mvc;

import cn.roadtrip.utilmodule.util.AccessMVCThreadSet;
import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

/**
 * 用户请求访问拦截器，
 */
@Component
@Slf4j
public class UserAccessControllerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response,
            Object handler) throws ServletException, IOException {
        log.info("在拦截器中提示");
        String direct = request.getHeader("direct");
        String clientCode = request.getHeader("clientCode");
        String utoken = request.getHeader("utoken");
        String aut = request.getHeader("aut");//身份
        try {
            if (utoken.equals("zwkdev"))
                return true;
        } catch (Exception e) {
        }
        int count = 0;
        if (direct == null) {
            count++;
        }
        if (clientCode == null) {
            count++;
        }
        if (utoken == null) {
            count++;
        }
        if (aut == null) {
            count++;
        }
        log.info("count->{}", count);

        if (count >= 1) {
            Gson gson = new Gson();

            log.info("print-out");
            //{"code":"acl-err","msg":"????","suc":false,"totalCount":0,"createTime":1704382421762,"ext_msg":""}
            response.getWriter().print(new String(gson.toJson(Map.of(
                    "code","acl-err",
                    "msg","acl-err",
                    "suc",false,
                    "totalCount",0,
                    "createTime",System.currentTimeMillis(),
                    "ext_msg",""
            )).getBytes(), "utf-8"));
            return false;
        }
        AccessMVCThreadSet.CurrentThreadLocal.set(new AccessMVCThreadSet.AccessControllerHeader(
                direct, clientCode, utoken, aut
        ));
        return true;
    }
}
